<template>
  <el-dialog v-if="visible" :title="title" :visible.sync="visible" width="600px" :before-close="handleClose"
    append-to-body>
    <el-form class="form-container" ref="form" :model="form" :rules="rules" label-suffix="：" label-width="110px">
      <!-- 上线后一定会重新修改，改成啥样未知 -->
      <el-form-item :label="type == 'edit' ? '修改客户单位' : '新增客户单位'" prop="editApp" v-if="type == 'add' || isEdit">
        <el-radio-group :disabled="!isEdit" v-model="editApp" @change="handleChangeIsNewApp">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="editApp == 1" label="客户单位" prop="appName">
        <el-input :disabled="!isEdit" placeholder="请填写客户单位名称" v-model="form.appName"></el-input>
      </el-form-item>
      <el-form-item v-else label="客户单位" prop="appId">
        <el-select :disabled="!isEdit" style="width: 100%" v-model="form.appId" placeholder="请选择客户单位" clearable
          @change="handleChangeApp">
          <el-option v-for="item in appList" :key="item.appId" :label="item.appName" :value="item.appId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="cardTypeName">
        <el-input :disabled="!isEdit" v-model="form.cardTypeName" placeholder="请输入项目名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="权益" prop="rightList">
        <template v-if="cardVersion == '1'">
          <el-checkbox-group v-model="form.rightList" :disabled="true">
            <el-checkbox v-for="(item, index) in cardVersion == '1'
                ? localRightList
                : allRightsList" :label="item.rightId" :key="index">{{ item.rightName }}</el-checkbox>
          </el-checkbox-group>
          <span v-if="cardVersion == '1'" class="tips">注：1.0版本的职途权益不允许更改</span>
        </template>
        <template v-if="cardVersion == '2'">
          <el-cascader ref="cascader" style="width: 100%" v-model="form.rightList" :disabled="!isEdit"
            :options="allRightsList" :props="{
              multiple: true,
              label: 'rightName',
              value: 'rightId',
              children: 'children',
              emitPath: false,
            }" collapse-tags clearable @change="handleChangeRights"></el-cascader>
        </template>
      </el-form-item>
      <!-- <el-form-item class="checkbox" label="相关顾问" prop="consultantList">
        <div class="flex" v-if="consultantList.length">
          <el-tag
            v-for="(item, index) in consultantList"
            :key="index"
            type="info"
          >
            {{ item.consultantName }}
          </el-tag>
        </div>
        <div v-else>暂无顾问</div>
      </el-form-item> -->
      <el-form-item v-if="showPerson" label="销售" prop="adminResString">
        <el-input :disabled="!isEdit" v-model="form.adminResString" placeholder="请选择销售" clearable
          @focus="handleFocusPerson" @clear="handleClearAdminRes"></el-input>
      </el-form-item>
      <el-form-item v-if="showPerson" label="顾问" prop="consultant">
        <el-select v-model="form.consultantIdList" multiple placeholder="请选择" @focus="chooseConsultant"
          :disabled="!isEdit">
          <el-option v-for="(item, index) in consultantOptions" :key="index" :label="item.consultantName"
            :value="item.consultantId">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="tips">
      提示：
      <div class="tips-text">
        客户单位和项目名称的关系相当于大学与二级学院的关系，为了以后的续费问题而设计
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="type == 'edit' && showEditBtn" type="primary" @click="handleCanEdit">编辑</el-button>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" v-if="!showEditBtn" @click="handleConfirm">确定</el-button>
    </div>
    <PersonSelect :visible.sync="personSelectVisible" width="70%" :selectedArr="selectedArr" :component="dataType"
      :multiple="true" @cancel="cancel" @confirm="selectConfirm"></PersonSelect>
  </el-dialog>
</template>

<script>
import {
  rightsList,
  applicationList,
  getRightsTree,
  consultantList,
  getConsultantNameList,
  getCardTypeConsultantList,
} from "@/api/index";
export default {
  components: { PersonSelect: () => import("@/components/PersonSelect") },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    showPerson: {
      type: Boolean,
      default: false,
    },
    projectInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.rightsListFn();
        this.applicationListFn();
        this.getProjectInfo();
      }
    },
  },
  data() {
    return {
      title: "新增项目",
      personSelectVisible: false,
      showEditBtn: false,
      type: "add",
      allRightsList: [],
      consultantList: [],
      appList: [],
      dataType: "el-dialog",
      selectedArr: [],
      editApp: 1,
      isEdit: false,
      form: {
        appName: "",
        appId: "",
        cardTypeName: "",
        cardType: 0, // 这个是写死0，因为项目一定是新增
        rightList: [],
        adminRels: [],
        adminResString: "",
        consultantIdList: [],
        cardVersion: "2", // 新增的时候默认就是2
      },
      consultantOptions: [],
      selectedRightList: [],
      cardVersion: "2",
      localRightList: [],
      rules: {
        appName: [
          {
            required: true,
            message: "请填写客户单位",
            trigger: "blur",
          },
        ],
        appId: [
          {
            required: true,
            message: "请选择客户单位",
            trigger: "change",
          },
        ],
        cardTypeName: [
          {
            required: true,
            message: "请填写项目名称",
            trigger: "blur",
          },
        ],
        rightList: [
          {
            type: "array",
            required: true,
            message: "请选择权益",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {},
  methods: {
    handleClearAdminRes(val) {
      this.form.adminRels = [];
      console.log("handleClearAdminRes", val);
    },
    chooseConsultant() {
      this.getConsultantNameListFn();
    },
    async getCardTypeConsultantListFn(cardType) {
      const params = {
        examineStatus: 10,
        cardType: cardType,
      };
      const res = await getCardTypeConsultantList(params);
      if (res.code == 200) {
        console.log("res", res);
        let temp = [];
        res.data.forEach((item) => {
          temp.push(item.consultantId);
        });
        this.form.consultantIdList = temp;
      }
    },
    async getConsultantNameListFn() {
      const params = {
        pageNo: 1,
        pageSize: 1000,
      };
      const res = await getConsultantNameList(params);
      if (res.code == 200) {
        console.log("res", res);
        this.consultantOptions = res.data;
      }
    },
    handleChangeRights() {
      const map = {};
      const checkedNodes = this.$refs.cascader.getCheckedNodes();
      const temp = [];
      checkedNodes.forEach((item) => {
        if (!map[+item.value]) {
          temp.push({
            rightId: +item.value,
          });
          map[+item.value] = true;
          // 处理半选节点，半选的阶段也要获取给到服务端
          if (item.parent && item.parent.value) {
            temp.push({
              rightId: +item.parent.value,
            });
            map[+item.parent.value] = true;
          }
        }
      });
      this.selectedRightList = temp;
    },
    handleChangeApp(val) {
      const temp = this.appList.find((item) => item.appId == val);
      if (temp) {
        this.form.appName = temp.appName;
      }
    },
    handleCanEdit() {
      this.title = "编辑项目";
      this.isEdit = true;
      this.showEditBtn = false;
    },
    getRightsTreeFn() {
      const params = {
        cardType: this.projectInfo.cardType,
      };
      getRightsTree(params).then((res) => {
        if (res.code == 200) {
          const arr1 = [],
            arr2 = [];
          res.data.forEach((item) => {
            arr1.push(item.rightId);
            item.children.forEach((_item) => {
              arr2.push(_item.rightId);
            });
          });
          this.form.rightList = arr2;
        }
      });
    },
    consultantListFn() {
      const params = {
        pageNo: 1,
        pageSize: 1000,
        searchConsultantRange: "10",
        cardType: this.form.cardType,
      };
      consultantList(params).then((res) => {
        if (res.code == 200) {
          this.consultantList = res.data;
        }
      });
    },
    getProjectInfo() {
      this.getConsultantNameListFn();

      if (!this.projectInfo) {
        this.title = "新增项目";
        this.type = "add";
        this.showEditBtn = false;
        this.isNew = 1;
        this.isEdit = true;
        this.selectedArr = []; // 如果是新增则把这个置空
        this.form.consultantIdList = []; // 新增的时候把顾问回显字段置空
      } else {
        console.log("this.projectInfo", this.projectInfo);

        this.title = "项目详情";
        this.type = "edit";
        this.showEditBtn = true;
        this.isNewApp = 0;
        this.isEdit = false;
        this.form = {
          isNewApp: 0,
          appName: this.projectInfo.appName,
          appId: this.projectInfo.appId,
          cardTypeName: this.projectInfo.cardName,
          cardType: this.projectInfo.cardType,
          rightList: this.projectInfo.rightList,
          adminRels: this.projectInfo.adminRels,
          adminResString: this.projectInfo.adminResString,
          cardVersion: this.projectInfo.cardVersion,
        };
        this.getCardTypeConsultantListFn(this.projectInfo.cardType);
        this.cardVersion = this.projectInfo.cardVersion;
        this.getRightsTreeFn();
        this.consultantListFn();
        let temp1 = [];
        const temp2 = this.projectInfo.adminRels.map((item) => {
          temp1.push(item.adminName);
          return {
            id: item.adminId,
            name: item.adminName,
          };
        });
        this.selectedArr = temp2;
        this.form.adminResString = temp1.join("，");
        if (Array.isArray(this.projectInfo.rightList)) {
          if (this.cardVersion == "1") {
            this.localRightList = this.projectInfo.rightList;
          }
          this.form.rightList = this.projectInfo.rightList.map((item) => {
            return item.rightId;
          });
        } else {
          this.form.rightList = [];
        }
      }
    },
    handleFocusPerson() {
      this.personSelectVisible = true;
    },
    cancel() {
      this.personSelectVisible = false;
    },
    handleChangeIsNewApp() {
      if (this.type == "add") {
        this.form.appId = "";
      }
    },
    selectConfirm(e) {
      let temp1 = [];
      const temp2 = e.map((item) => {
        temp1.push(item.name);
        return {
          adminId: item.id,
          adminName: item.name,
        };
      });
      this.form.adminRels = temp2;
      this.form.adminResString = temp1.join("，");
    },
    applicationListFn() {
      applicationList()
        .then((res) => {
          if (res.code == 200) {
            this.appList = res.data;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async rightsListFn() {
      this.loading = true;
      const res = await rightsList();
      if (res.code == 200) {
        res.data.forEach((item) => {
          item.rightId = item.rightId + "";
        });
        this.allRightsList = res.data;
      }
    },
    handleClose() {
      this.form.rightList = [];
      this.handleReset();
      this.$refs.form.clearValidate();
      this.$emit("update:visible", false);
    },
    handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm("请确认所填写的内容是否正确?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              if (this.isNewApp == 1) {
                this.form.appId = 0;
              }
              const params = {
                ...this.form,
                selectedRightList: this.selectedRightList,
              };
              this.$emit("confirm", JSON.parse(JSON.stringify(params)));
              this.handleReset();
            })
            .catch(() => {});
        } else {
          return false;
        }
      });
    },
    handleReset() {
      this.form.appName = "";
      this.form.appId = "";
      this.form.cardTypeName = "";
      this.form.rightList = [];
      this.form.adminRels = [];
      this.form.adminResString = "";
      this.isEdit = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.form-container {
  padding: 24px 24px 0 24px;
  max-height: 450px;
  overflow-y: auto;
  ::v-deep .el-input.is-disabled .el-input__inner {
    color: #555;
  }
  ::v-deep .el-checkbox__input.is-disabled + span.el-checkbox__label {
    color: #555;
  }
  ::v-deep .el-select {
    width: 100%;
  }
  ::v-deep .el-cascader__tags {
    box-sizing: border-box;
    padding: 8px 15px 0 15px;
  }
  ::v-deep .el-select__tags {
    box-sizing: border-box;
    padding: 8px 15px 0 15px;
  }
}
::v-deep .el-tag.el-tag--info {
  margin: 0 8px 8px 0;
  color: #333;
}
.tips {
  color: $grey-7;
  padding: 0 24px 24px 24px;
  &-text {
    line-height: 26px;
  }
}
</style>
